package com.sys.basics.utils.quartz;

import com.sys.basics.config.constant.ScheduleConstant;
import com.sys.basics.utils.ApplicationContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ScheduleRunnableUtils implements Runnable {
    private Object target;
    private Method method;
    private String params;
    private String methodName = ScheduleConstant.METHOD_NAME;

    public ScheduleRunnableUtils(String beanName, String params) throws NoSuchMethodException {
        this.target = ApplicationContextUtils.getBean(beanName);
        this.params = params;

        if (StringUtils.isNotBlank(params)){
            this.method = target.getClass().getDeclaredMethod(methodName,String.class);
        }else {
            this.method = target.getClass().getDeclaredMethod(methodName);
        }
    }

    @Override
    public void run() {
        try {
            ReflectionUtils.makeAccessible(method);
            if (StringUtils.isNotBlank(params)){
                method.invoke(target,params);
            }else {
                method.invoke(target);
            }
        } catch (IllegalAccessException e) {
            throw new RuntimeException("执行定时任务失败", e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("执行定时任务失败", e);
        }
    }
}
